package com.ins1st.plus.web.user;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ins1st.plus.api.system.user.entity.SysUser;
import com.ins1st.plus.api.system.user.service.SysUserApi;
import com.ins1st.plus.base.BaseController;
import com.ins1st.plus.core.annotation.Req4Json;
import com.ins1st.plus.core.annotation.Req4Model;
import com.ins1st.plus.util.PageFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @program: ins1st-plus
 * @description: 用户控制层
 * @author: coderSun
 * @create: 2019-09-06 15:17
 **/
@Controller
@RequestMapping(value = "/sys/user")
public class SysUserController extends BaseController {

    private static final String VIEW = "pages/sys/user/";

    @Reference
    SysUserApi sysUserApi;


    /**
     * 用户管理主页
     *
     * @return
     */
    @Req4Model(value = "/index")
    public String index() {
        return VIEW + "user_index.html";
    }

    /**
     * 添加页
     *
     * @return
     */
    @Req4Model(value = "/add")
    public String add() {
        return VIEW + "user_add.html";
    }

    /**
     * 编辑页
     *
     * @return
     */
    @Req4Model(value = "/edit")
    public String edit(Integer id, Model model) {
        SysUser sysUser = this.sysUserApi.getById(id);
        model.addAttribute("user", sysUser);
        return VIEW + "user_edit.html";
    }


    /**
     * 用户集合
     *
     * @param sysUser
     * @return
     */
    @Req4Json(value = "/list")
    public Object list(SysUser sysUser, HttpServletRequest request) {
        IPage<SysUser> page = sysUserApi.page(sysUser, PageFactory.defaultPage());
        return PageFactory.createPage(page);
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Req4Json(value = "/delete")
    public Object delete(Integer id) {
        this.sysUserApi.removeById(id);
        return success();
    }


    /**
     * 更新
     *
     * @param sysUser
     * @return
     */
    @Req4Json(value = "/update")
    public Object update(SysUser sysUser) {
        this.sysUserApi.update(sysUser);
        return success();
    }


    /**
     * 保存
     *
     * @param sysUser
     * @return
     */
    @Req4Json(value = "/save")
    public Object save(SysUser sysUser) {
        sysUser.setUserPassword(SecureUtil.md5(sysUser.getUserName() + "-" + sysUser.getUserPassword()));
        sysUser.setLoginStatus("1");
        sysUser.setCreateTime(new Date());
        this.sysUserApi.save(sysUser);
        return success();
    }

}
